/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

//
//  AppDelegate.m
//  bsl-sdk
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//

#import "AppDelegate.h"
#import "NavigationViewController.h"

#import <chameleon-ios-sdk/ChamleonSDK.h>
#import "OpenShare.h"
#import <OpenShare/OpenShare+Weibo.h>
#import <OpenShare/OpenShare+Weixin.h>
#import <Cordova/CDVPlugin.h>

#import "OpenShareHeader.h"


/* 需要知道的事：
 1，证书需要打入至少两台的本地测试机  ，要开发者证书
 2，updateDeviceTokenForPushNotificationByAsychronous 的token 的传入是否正确
 3,  updateDeviceTokenForPushNotificationByAsychronous  与登陆是否需要分先后顺序
*/

@implementation AppDelegate

- (id)init{
    /** If you need to do any extra app-specific initialization, you can do it here
     *  -jm
     **/
    NSLog(@"NSHomeDirectory%@",NSHomeDirectory());
    NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

    int cacheSizeMemory = 8 * 1024 * 1024; // 8MB
    int cacheSizeDisk = 32 * 1024 * 1024; // 32MB
#if __has_feature(objc_arc)
        NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
#else
        NSURLCache* sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease];
#endif
    [NSURLCache setSharedURLCache:sharedCache];

    self = [super init];
    return self;
}

-(void)pushViewController:(UIViewController*)viewController animated:(BOOL)animated{
    [self.navController pushViewController:viewController animated:animated];
}

-(void)presentViewController:(UIViewController*)viewController animated:(BOOL)animated{
    [self.navController dismissModalViewControllerAnimated:NO];
    [self.navController presentViewController:viewController animated:animated completion:nil];
}

#pragma mark UIApplicationDelegate implementation

/**
 * This is main kick off after the app inits, the views and Settings are setup here. (preferred - iOS4 and up)
 */
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
    //添加qq AppId
    [OpenShare connectQQWithAppId:@"1103194207"];
    //添加微博AppKey
    [OpenShare connectWeiboWithAppKey:@"3219551618"];
    //添加微信AppId
    [OpenShare connectWeixinWithAppId:@"wxc29b4d7f1d6ccc50"];
    [application cancelAllLocalNotifications];
    
    [application setApplicationIconBadgeNumber:0];
  

    CGRect screenBounds = [[UIScreen mainScreen] bounds];

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        
        [application setStatusBarStyle:UIStatusBarStyleLightContent];
    }
    
    self.window = [[UIWindow alloc] initWithFrame:screenBounds];
    self.window.autoresizesSubviews = YES;
    
    self.navController=[[NavigationViewController alloc] init];
    [self.navController setNavigationBarHidden:YES];
    self.window.rootViewController = self.navController;
    
    
    ZillaAccessData* activeSession=[ZillaAccessData activeSession];
#ifdef DEBUG
    activeSession.sandBoxEnviroment=YES;
#else
    activeSession.sandBoxEnviroment=NO;
#endif
    
#ifndef PRODUCTION_APP
//    activeSession.appKey=@"3cab23944e145900508fb43b7f862b49";
//    activeSession.appSecret=@"e1ac12d9-2ef4-41bb-a097-09826d251c0a";
//    activeSession.urlSchemeSuffix =@"10.108.1.217:18860";
    
    activeSession.appKey=@"9004e952ff699c917909a341e5ae8a4f";
    activeSession.appSecret=@"fb1844bf-d737-4b40-b073-2150440408f9";
    activeSession.urlSchemeSuffix =@"bsl.foreveross.com:18860";
#else

    activeSession.appKey=@"9004e952ff699c917909a341e5ae8a4f";
    activeSession.appSecret=@"fb1844bf-d737-4b40-b073-2150440408f9";
    activeSession.urlSchemeSuffix =@"115.28.1.119:18860";

#endif
    
    CApplication* cApplication=[CApplication sharedApplication];
    [cApplication initModulesConfig];
    
    DBStorageHelper* dbHelper=[DBStorageHelper standandStorage];
    RoutingParserHelper* routingParserHelper=[RoutingParserHelper sharedRouting];

    for(CModule* module in [cApplication modules]){
        @autoreleasepool {
            [dbHelper configStorageWithModule:module.identifier];
            [routingParserHelper readConfig:[module routingJson] moduleIdentifier:module.identifier moduleName:module.name];
        }
    }


    [cApplication application:self didFinishLaunchingWithOptions:launchOptions];
    
    [[CApplication sharedApplication] startModule];
    [self.window makeKeyAndVisible];
    
    [[CApplication sharedApplication] dispatchAsyncModules];
    
    return YES;
}

//HNA
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken{
    
    NSLog(@"application token did success");
    if ([_deviceToken length]<1)
        return;
    
    [[CApplication sharedApplication] application:application didRegisterForRemoteNotificationsWithDeviceToken:_deviceToken];
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"application token did failed:%@\n",error);
    
    [[CApplication sharedApplication] application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    [application cancelAllLocalNotifications];
    [[CApplication sharedApplication] application:application didReceiveRemoteNotification:userInfo];
}


- (void)applicationDidBecomeActive:(UIApplication *)application{
    [[CApplication sharedApplication] applicationDidBecomeActive:application];
}

- (void)applicationWillResignActive:(UIApplication *)application{
    [[CApplication sharedApplication] applicationWillResignActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application{
    [[CApplication sharedApplication] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application{
    [[CApplication sharedApplication] applicationWillEnterForeground:application];
}

- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url{
    if ([OpenShare handleOpenURL:url]) {
        return YES;
    }
    return YES;
}

// repost the localnotification using the default NSNotificationCenter so multiple plugins may respond
- (void) application:(UIApplication*)application
    didReceiveLocalNotification:(UILocalNotification*)notification{
    // re-post ( broadcast )
    
    [[NSNotificationCenter defaultCenter] postNotificationName:CDVLocalNotification object:notification];

    
//    [[CApplication sharedApplication] application:application didReceiveLocalNotification:notification];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReceivedMessagePush" object:nil];
    
}

- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window{
    // iPhone doesn't support upside down by default, while the iPad does.  Override to allow all orientations always, and let the root view controller decide what's allowed (the supported orientations mask gets intersected).
    NSUInteger supportedInterfaceOrientations = (1 << UIInterfaceOrientationPortrait) | (1 << UIInterfaceOrientationLandscapeLeft) | (1 << UIInterfaceOrientationLandscapeRight) | (1 << UIInterfaceOrientationPortraitUpsideDown);

    return supportedInterfaceOrientations;
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

@end
